﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using ProTrack.Api.Helper;
using ProTrack.Dto;
using ProTrack.Entity;
using ProTrack.IServices.Product;
using ProTrack.Report;
using ProTrack.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ProTrack.Api.Controllers
{
    /// <summary>
    /// 物料产品服务接口
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class ItemController : ControllerBase
    {
        public ItemController(IItemServices services, LogHelper LogHelper)
        {
            Services = services;
            this.LogHelper = LogHelper;
        }

        public IItemServices Services { get; }
        public LogHelper LogHelper { get; }



        /// <summary>
        /// 获取所有物料产品
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAll")]
        public async Task<IActionResult> GetAll()
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.GetAllAsync();
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("物料产品-获取所有", ex, HttpContext);
            }


            return Ok(status);
        }


        /// <summary>
        /// 分页获取物料产品
        /// </summary>
        /// <param name="PageIndex">当前页</param>
        /// <param name="PageSize">页大小</param>
        /// <param name="ItemCode">编码</param>
        /// <param name="ItemName">产品物料名称</param>
        /// <param name="ItemTypeId">类别Id</param>
        /// <returns></returns>

        [HttpGet]
        public async Task<IActionResult> Get([FromQuery] int PageIndex, [FromQuery] int PageSize, [FromQuery] string ItemCode, [FromQuery] string ItemName, [FromQuery] int ItemTypeId)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                ItemCode = ItemCode ?? "";
                ItemName = ItemName ?? "";

                var list = await Services.GetAsync(PageIndex, PageSize,ItemCode, ItemName, ItemTypeId);
                status.Data = list;
                status.Count = await Services.GetCountAsync(ItemCode, ItemName, ItemTypeId);
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("物料产品-分页获取", ex, HttpContext);
            }

            return Ok(status);
        }


        /// <summary>
        /// 根据物料或产品Id获取BOM组成
        /// </summary>
        /// <param name="ItemId"></param>
        /// <returns></returns>
        [HttpGet("GetProductBombyId")]
        public async Task<IActionResult> GetProductBombyId( [FromQuery] string ItemId)
        {
            var status = BaseStatus.CreateInstance();
            try
            {

                var list = await Services.GetProductBombyIdAsync(ItemId);
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("物料产品-获取BOM组成", ex, HttpContext);
            }

            return Ok(status);
        }



        /// <summary>
        /// 获取当前仓库下的物料产品
        /// </summary>
        /// <param name="PageIndex">当前页</param>
        /// <param name="PageSize">每页显示条数</param>
        /// <param name="ItemCode">物料编码</param>
        /// <param name="ItemName">物料名称</param>
        /// <param name="ItemTypeId">物料类别：-1全部 </param>
        /// <param name="WareHouseId">当前仓库Id</param>
        /// <returns></returns>

        [HttpGet("GetItemStock")]
        public async Task<IActionResult> GetItemStock([FromQuery] int PageIndex, [FromQuery] int PageSize, [FromQuery] string ItemCode, [FromQuery] string ItemName, [FromQuery] int ItemTypeId, [FromQuery] int WareHouseId)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                ItemCode = ItemCode ?? "";
                ItemName = ItemName ?? "";

                var list = await Services.GetItemStockAsync(PageIndex, PageSize, ItemCode, ItemName, ItemTypeId, WareHouseId);
                status.Data = list;
                status.Count = await Services.GetItemStockCountAsync(ItemCode, ItemName, ItemTypeId, WareHouseId);
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("物料产品库存项-分页获取", ex, HttpContext);
            }

            return Ok(status);
        }




        /// <summary>
        /// 新增物料产品
        /// </summary>
        /// <param name="model">设备类型</param>
        /// <param name="ProductBomString">BOM 集合，使用字符串序列化数组</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Add([FromForm] Item model,[FromForm] string ProductBomString)
        {
            var status = BaseStatus.CreateInstance();
            List<ProductBom> list = new List<ProductBom>() ;
            try
            {
                if (!string.IsNullOrEmpty(ProductBomString))
                {
                    list = JsonConvert.DeserializeObject<List<ProductBom>>(ProductBomString);
                    list.ForEach(x => {
                        x.CreateTime = StringHelper.GetTimeNow();
                        x.Creator = User.Identity.Name;
                        //主表Id由于是自增，由内部方法自动赋值,无需手动介入
                    });
                }
                model.CreateTime = StringHelper.GetTimeNow();
                model.Creator = User.Identity.Name;
                var result = await Services.AddAsync(model,list);
                if (result)
                {
                    status.Msg = "新增成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "产品新增失败,请检查数据。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("产品管理-物料产品新增", ex, HttpContext);
            }
            return Ok(status);


        }


        /// <summary>
        /// 修改物料产品
        /// </summary>
        /// <param name="model">单位模型</param>
        /// <param name="ProductBomString">BOM 集合，使用字符串序列化数组</param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> Update([FromForm] Item model, [FromForm] string ProductBomString)
        {
            var status = BaseStatus.CreateInstance();
            List<ProductBom> list = new List<ProductBom>();
            try
            {
                if (!string.IsNullOrEmpty(ProductBomString))
                {
                    list = JsonConvert.DeserializeObject<List<ProductBom>>(ProductBomString);
                    list.ForEach(x => {
                        x.UpdateTime = StringHelper.GetTimeNow();
                        x.Updater = User.Identity.Name;

                        //重新将编辑的主表Id 赋值给从表
                        x.ItemId = model.Id;
                    });
                }
                model.UpdateTime = StringHelper.GetTimeNow();
                model.Updater = User.Identity.Name;
                var isSuccess = await Services.UpdateAsync(model,list);
                if (isSuccess)
                {
                    status.Msg = "修改成功";

                    //操作日志
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "修改失败，请检查数据。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("物料产品-修改", ex, HttpContext);
            }

            return Ok(status);
        }




        /// <summary>
        /// 批量删除物料产品
        /// </summary>
        /// <param name="Ids">Id数组</param>
        /// <returns></returns>
        [HttpDelete("DelAll")]
        public async Task<IActionResult> DelAll([FromForm] string Ids)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var arr = Ids.SplitId();
                var isSuccess = await Services.DeleteAsync(arr);
                if (isSuccess)
                {
                    status.Msg = "删除成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败，请稍后重试。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("物料产品-批量删除", ex, HttpContext);
            }

            return Ok(status);
        }



        /// <summary>
        /// 删除物料产品
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete]

        public async Task<IActionResult> Del([FromForm] int Id)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var isSuccess = await Services.DeleteAsync(Id);
                if (isSuccess)
                {
                    status.Msg = "删除成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败，请稍后重试。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("物料产品-删除", ex, HttpContext);
            }

            return Ok(status);
        }


        /// <summary>
        /// 导出
        /// </summary>
        /// <returns></returns>
        [HttpGet("Export")]
        public async Task<IActionResult> Export()
        {
            try
            {

                var list = await Services.GetAllAsync();
                var TitleArray = new ReportDomain[] {
                    new ReportDomain{ Title="序号",Fileld="No"},
                    new ReportDomain{ Title="产品编码",Fileld="ItemCode"},
                    new ReportDomain{ Title="产品名称",Fileld="ItemName"},
                    new ReportDomain{ Title="线别",Fileld="LineType"},
                    new ReportDomain{ Title="供应商",Fileld="Vendor"},
                    new ReportDomain{ Title="规格",Fileld="Spec"},
                    new ReportDomain{ Title="型号",Fileld="Model"},
                    new ReportDomain{ Title="单位",Fileld="UnitOfMeasure"},
                    new ReportDomain{ Title="品类",Fileld="Kind"},
                    new ReportDomain{ Title="产品/物料",Fileld="ItemOrProduct"},
                    new ReportDomain{ Title="类别",Fileld="ItemTypeName"},
                    new ReportDomain{ Title="最低库存量",Fileld="MinStock"},
                    new ReportDomain{ Title="最大库存量",Fileld="MaxStock"},
                    new ReportDomain{ Title="采购价",Fileld="PurchasePrice"},
                    new ReportDomain{ Title="销售价",Fileld="SalePrice"},
                    new ReportDomain{ Title="有效日期",Fileld="EffectiveDate"},
                    new ReportDomain{ Title="最后修改",Fileld="LastUpdateTime"},
                    new ReportDomain{ Title="备注",Fileld="Remark"},
                };
                var fileArray = BaseReport.Export(list, "产品物料信息", TitleArray);

                return File(new System.IO.MemoryStream(fileArray), "application/octet-stream", "产品物料信息.xls");
            }
            catch (Exception ex)
            {

                //此处应当日志记录
                await LogHelper.WriteErrorLog("物料产品-导出", ex, HttpContext);
                return new JsonResult(BaseStatus.CreateInstance(-1, "导出失败，服务器异常请稍后再试！"));
            }

        }


    }
}
